package com.chungkui.bond.authmanager.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chungkui.bond.authmanager.bean.Client;
import com.chungkui.bond.authmanager.bean.Permission;
import com.chungkui.bond.authmanager.bean.PermissionClient;
import com.chungkui.bond.authmanager.service.ClientService;
import com.chungkui.bond.authmanager.service.PermissionClientService;
import com.chungkui.bond.authmanager.service.PermissionService;
import com.chungkui.bond.common.core.api.ResBus;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


@RestController
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    PermissionService permissionService;
    @Autowired
    PermissionClientService permissionClientService;

    @RequestMapping("/list")
    public Object list(Permission permission) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.setEntity(permission);
        return ResBus.success(permissionService.list(queryWrapper));
    }

    @RequestMapping("/listPage")
    public Object listPage(Permission permission, Page page) {
        return ResBus.success(permissionService.pageWithClients(page, permission.getClientId()));
    }

    @RequestMapping("/delete/{id}")
    public Object delete(@PathVariable("id") String id) {
        return ResBus.success(permissionService.removeById(id));
    }

    @RequestMapping("/saveclients")
    public Object saveclients(String clients, String id) {
        if (StringUtils.isNotEmpty(clients) && StringUtils.isNotEmpty(id)) {
            List<PermissionClient> permissionClients = Lists.newArrayList();
            for (String client : StringUtils.split(clients, ",")) {
                PermissionClient permissionClient = new PermissionClient();
                permissionClient.setPermissionId(id);
                permissionClient.setClientId(client);
                permissionClients.add(permissionClient);
            }
            permissionClientService.saveList(permissionClients);
        }
        return ResBus.success(true);
    }
}

